public class Solution {
    boolean[][] vis;
    int m, n;
    char[] word;
    int[] dx = {0,0,-1,1};
    int[] dy = {-1,1,0,0};

    public boolean exist(char[][] board, String _word) {
        m = board.length;
        n = board[0].length;
        vis = new boolean[m][n];
        word = _word.toCharArray();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if(board[i][j] == word[0]){
                    vis[i][j] = true; // 正确标记起始位置
                    if (dfs(board, i, j, 1)) {
                        return true;
                    }
                    vis[i][j] = false; // 回溯时重置起始位置
                }
            }
        }
        return false;
    }

    private boolean dfs(char[][] board, int i, int j, int pos) {
        if(pos == word.length){
            return true;
        }
        for (int k = 0; k < 4; k++) {
            int x = i+dx[k];
            int y = j+dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && board[x][y] == word[pos]){
                vis[x][y] = true;
                if (dfs(board,x,y,pos+1)){
                    return true;
                }
                vis[x][y] = false;
            }
        }
        return false;
    }
}
